<template>
  <p-modal
    v-model="visible"
    :body-style="{
      height: '530px',
    }"
    :title="title"
    :width="1000"
    :mask-closable="false"
    :dialog-style="{ top: '40px' }"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <div>
      <div class="form-div">
        <div style="height: 70px; display: inline-block; width: 85%">
          <div class="row">
            <div class="row-div">
              <p-input v-model="form.customerName" class="row-input" />
              <span class="row-span">客户简称</span>
            </div>
            <div class="row-div">
              <p-input v-model="form.modelName" class="row-input" />
              <span class="row-span">Model Name</span>
            </div>
            <div class="row-div">
              <p-input v-model="form.modelInfoName" class="row-input" />
              <span class="row-span">机种</span>
            </div>
          </div>
          <div class="row">
            <div class="row-div">
              <SelectDefault
                v-model="form.application"
                class="row-input"
                code="application"
              />
              <span class="row-span">应用别</span>
            </div>
            <div class="row-div">
              <SelectDefault
                v-model="form.appearance"
                code="shape"
                class="row-input"
              />
              <span class="row-span"> 形态 </span>
            </div>
            <div class="row-div">
              <SelectDefault
                v-model="form.manufactureArea"
                code="production_place"
                class="row-input"
              />
              <span class="row-span"> 生产地 </span>
            </div>
          </div>
        </div>
        <div class="button-div">
          <div style="width: 44px; float: left">
            <p-button
              class="commonbutton"
              style="margin-bottom: 5px"
              type="primary"
              @click="searchTable"
            >
              搜索
            </p-button>
            <p-button class="commonbutton" @click="resForm">重置</p-button>
          </div>
        </div>
      </div>
      <!-- <p-button>新增客户</p-button> -->
      <p-table
        class="table-list-container"
        row-key="id"
        :columns="columns"
        :bordered="true"
        :scroll="{ x: 'calc(1400px + 20%)', y: 250 }"
        :data-source="dataSource"
        :pagination="paginationMixin"
        :row-selection="rowSelectionMixin"
        size="middle"
        @change="change"
      >
      </p-table>
    </div>
    <DialogBpForecastRelationList
      :value="currentRowInfo.value"
      :visible="visibleBpId"
      :time-range="timeRange"
      :is-edit="false"
      :condition="{
        relationId: currentRowInfo.row && currentRowInfo.row.bpRelationId,
        mforecastSalesId:
          currentRowInfo.row && currentRowInfo.row.mforecastSalesId,
      }"
      @cancel="(val) => (visibleBpId = val)"
      @change="(e) => confirmDialog(e)"
    />
    <DialogRpRelationList
      :value="currentRowInfo.value"
      :visible="visibleRpId"
      :time-range="timeRange"
      :is-edit="false"
      :condition="{
        relationId: currentRowInfo.row && currentRowInfo.row.rpRelationId,
        mforecastSalesId:
          currentRowInfo.row && currentRowInfo.row.mforecastSalesId,
      }"
      @cancel="(val) => (visibleRpId = val)"
      @change="(e) => confirmDialog(e)"
    />
  </p-modal>
</template>

<script>
import { postPriceChangeTableList } from '@/api/price.js';
import { createMonthArray } from '@/utils/time';
import mixinTable from '@/mixins/mixin-table.js';
import DrawerMixin from '@/views/price-change/components/mixin';
import DialogBpForecastRelationList from '@/components/dialog/DialogBpForecastRelationList.vue';
import DialogRpRelationList from '@/components/dialog/DialogRpRelationList.vue';
import ColumnsTooltip from '@/views/price-account/components/columnsTooltip.vue';

import monent from 'moment';
const defaultForm = {
  customerName: '',
  modelName: '',
  modelInfoName: '',
  appearance: '',
  manufactureArea: '',
  application: '',
};

export default {
  components: {
    DialogBpForecastRelationList,
    DialogRpRelationList,
  },
  mixins: [mixinTable, DrawerMixin],
  props: {
    resKey: {
      type: Boolean,
      default: false,
    },
    keyArray: {
      type: Array,
      default: () => [],
    },
    timeRange: {
      type: Array,
      default: () => [],
    },
    title: {
      type: String,
      default: '选择需要变更的记录',
    },
    value: {
      type: [String, Number],
      default: undefined,
    },
    visible: {
      type: Boolean,
      default: false,
    },
    index: {
      type: Number,
      default: 0,
    },
    forms: {
      type: Object,
      default: () => ({}),
    },
    deleteKeys: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      form: {
        customerName: '',
        modelName: '',
        modelInfoName: '',
        appearance: '',
        manufactureArea: '',
        application: '',
        salesGroupName: this.forms.salesGroup,
      },
      isEdit: false,
      resDateArr: [],
      diffFilterKeys: [],
      Keys: [],
      visibleBpId: false,
      visibleRpId: false,
      currentRowInfo: {},
    };
  },
  computed: {
    shapeOptions() {
      return this.$store.state.dictionary.dict['shape'] || {};
    },
    productionPlaceOptions() {
      return this.$store.state.dictionary.dict['production_place'] || {};
    },
    // modelOptions() {
    //   return this.$store.state.dictionary.dict['plan_detail_model'] || {};
    // },
    applicationOptions() {
      return this.$store.state.dictionary.dict['application'] || {};
    },
    factoryOptions() {
      return this.$store.state.dictionary.dict['factory_code'] || {};
    },
    categoryOptions() {
      return this.$store.state.dictionary.dict['category'] || {};
    },
    columns() {
      const columns = [
        {
          align: 'center',
          title: '序号',
          width: 60,
          // customRender(t, r, index) {
          //   return parseInt(index) + 1;
          // },
          customRender: (t, r, index) => {
            if (this.totalAllIndex.includes(index)) {
              return {
                children: (
                  <div style="display: flex;justify-content: flex-start;">
                    汇总
                  </div>
                ),
                attrs: {
                  colSpan: this.colIndex,
                },
              };
            }
            return parseInt(index) + 1;
          },
        },
        {
          align: 'center',
          title: 'M+9关系ID',
          dataIndex: 'm9RelationId',
          key: 'm9RelationId',
          width: 100,
          ellipsis: true,
          customRender: (value, row, index) => {
            const children = (
              <div>
                <ColumnsTooltip value={value} />
              </div>
            );
            return this.customRender(children, index);
          },
        },
        {
          align: 'center',
          title: '关联RP关系ID',
          dataIndex: 'rpRelationId',
          key: 'rpRelationId',
          width: 100,
          ellipsis: true,
          customRender: (value, row, index) => {
            const children = (
              <InputSearch
                value={{ key: value, label: value }}
                isEdit={false}
                isLink={true}
                vOn:search={() =>
                  this.openDialog('visibleRpId', {
                    value,
                    row,
                    index,
                    dataIndex: 'rpRelationId',
                  })
                }
              />
            );
            return this.customRender(children, index);
          },
        },
        {
          align: 'center',
          title: '关联BP关系ID',
          dataIndex: 'bpRelationId',
          key: 'bpRelationId',
          width: 100,
          ellipsis: true,
          customRender: (value, row, index) => {
            const children = (
              <InputSearch
                value={{ key: value, label: value }}
                isEdit={false}
                isLink={true}
                vOn:search={() =>
                  this.openDialog('visibleBpId', {
                    value,
                    row,
                    index,
                    dataIndex: 'bpRelationId',
                  })
                }
              />
            );
            return this.customRender(children, index);
          },
        },
        {
          align: 'center',
          title: '厂别',
          dataIndex: 'factoryCode',
          key: 'factoryCode',
          width: 80,
          ellipsis: true,
          customRender: (value, row, index) => {
            const children = (
              <div>
                <ColumnsTooltip value={this.factoryOptions[value]} />
              </div>
            );
            return this.customRender(children, index);
          },
        },
        {
          align: 'center',
          title: '客户简称',
          dataIndex: 'customerName',
          key: 'customerName',
          width: 80,
          ellipsis: true,
          customRender: (value, row, index) => {
            const children = (
              <div>
                <ColumnsTooltip value={value} />
              </div>
            );
            return this.customRender(children, index);
          },
        },
        {
          align: 'center',
          title: '机种',
          dataIndex: 'modelInfoName',
          key: 'modelInfoName',
          width: 80,
          ellipsis: true,
          customRender: (value, row, index) => {
            const children = (
              <div>
                <ColumnsTooltip value={value} />
              </div>
            );
            return this.customRender(children, index);
          },
        },
        {
          align: 'center',
          title: 'Model Name',
          dataIndex: 'modelName',
          key: 'modelName',
          width: 100,
          ellipsis: true,
          customRender: (value, row, index) => {
            const children = (
              <div>
                <ColumnsTooltip value={value} />
              </div>
            );
            return this.customRender(children, index);
          },
        },
        {
          align: 'center',
          title: '料号',
          dataIndex: 'materialCode',
          key: 'materialCode',
          width: 100,
          ellipsis: true,
          customRender: (value, row, index) => {
            const children = (
              <div>
                <ColumnsTooltip value={value} />
              </div>
            );
            return this.customRender(children, index);
          },
        },
        {
          align: 'center',
          title: '生产地',
          width: 80,
          dataIndex: 'manufactureArea',
          key: 'manufactureArea',
          ellipsis: true,
          customRender: (value, row, index) => {
            const children = (
              <div>
                <ColumnsTooltip value={this.productionPlaceOptions[value]} />
              </div>
            );
            return this.customRender(children, index);
          },
        },
        {
          align: 'center',
          title: '应用别',
          dataIndex: 'application',
          key: 'application',
          width: 80,
          ellipsis: true,
          customRender: (value, row, index) => {
            const children = (
              <div>
                <ColumnsTooltip value={this.applicationOptions[value]} />
              </div>
            );
            return this.customRender(children, index);
          },
        },
        {
          align: 'center',
          title: '模切比',
          width: 80,
          dataIndex: 'modelCutRate',
          key: 'modelCutRate',
          ellipsis: true,
          customRender: (value, row, index) => {
            const children = (
              <div>
                <ColumnsTooltip value={value} />
              </div>
            );
            return this.customRender(children, index);
          },
        },
        {
          align: 'center',
          title: '形态',
          dataIndex: 'appearance',
          key: 'appearance',
          width: 80,
          ellipsis: true,
          customRender: (value, row, index) => {
            const children = (
              <div>
                <ColumnsTooltip value={this.shapeOptions[value]} />
              </div>
            );
            return this.customRender(children, index);
          },
        },
        {
          align: 'center',
          title: '客户项目',
          dataIndex: 'item',
          key: 'item',
          width: 80,
          ellipsis: true,
          customRender: (value, row, index) => {
            const children = (
              <div>
                <ColumnsTooltip value={value} />
              </div>
            );
            return this.customRender(children, index);
          },
        },
        {
          align: 'center',
          title: '内部项目',
          dataIndex: 'innerItem',
          key: 'innerItem',
          width: 80,
          ellipsis: true,
          customRender: (value, row, index) => {
            const children = (
              <div>
                <ColumnsTooltip value={value} />
              </div>
            );
            return this.customRender(children, index);
          },
        },
        {
          align: 'center',
          title: '类别',
          dataIndex: 'category',
          key: 'category',
          width: 80,
          ellipsis: true,
          customRender: (value, row, index) => {
            const children = (
              <div>
                <ColumnsTooltip value={this.categoryOptions[value]} />
              </div>
            );
            return this.customRender(children, index);
          },
        },
        {
          align: 'center',
          title: '备注',
          width: 100,
          dataIndex: 'remark',
          key: 'remark',
          ellipsis: true,
          customRender: (value, row, index) => {
            const children = (
              <div>
                <ColumnsTooltip value={value} />
              </div>
            );
            return this.customRender(children, index);
          },
        },
      ];
      if (this.dateArr.length) {
        this.dateArr.forEach((date, i) => {
          columns.push({
            align: 'center',
            title: date,
            dataIndex: `priceMonth${i}`,
            width: 180,
            ellipsis: true,
            children: [
              {
                align: 'center',
                title: 'BP',
                dataIndex: `bpPriceMonth${date}`,
                key: `bpPrice${date}`,
                width: 60,
              },
              {
                align: 'center',
                title: 'RP',
                dataIndex: `rpPriceMonth${date}`,
                key: `rpPrice${date}`,
                width: 60,
              },
              {
                align: 'center',
                title: 'M+9',
                dataIndex: `priceMonth${date}`,
                key: `price${date}`,
                width: 60,
              },
              {
                align: 'center',
                title: '最新价格',
                dataIndex: `newPriceMonth${date}`,
                key: `newPrice${date}`,
                width: 60,
                ellipsis: true,
                customRender: (value, row, index) => {
                  const children = (
                    <div>
                      <ColumnsTooltip value={value} />
                    </div>
                  );
                  return this.customRender(children, index);
                },
                // scopedSlots: {
                //   customRender: `newPriceMonth${date}`,
                // },
                // customRender: (value, row, index) => {
                //   const children = (
                //     <div>
                //       <InputTable
                //         isEdit={this.isEdit}
                //         isNewPrice={true}
                //         value={value}
                //         vOn:change={e =>
                //           this.handleInputChange(
                //             e,
                //             value,
                //             row,
                //             index,
                //             `newPriceMonth${date}`
                //           )
                //         }
                //       />
                //     </div>
                //   );
                //   return {
                //     children,
                //   };
                // },
              },
            ],
          });
        });
      }
      // console.log(columns);
      return columns;
    },

    dateArr() {
      if (!this.dataSource.length) return [];
      const price = JSON.parse(this.dataSource[0].price);
      const priceKeys = Object.keys(price);
      const startTime = priceKeys[0];
      const endTime = priceKeys[priceKeys.length - 1];
      const ranges = createMonthArray([startTime, endTime]);
      return ranges;
    },
    isAccord() {
      const startTime = monent(this.forms.startTime).format('YYYY-MM');
      const endTime = monent(this.forms.endTime).format('YYYY-MM');
      const ranges = createMonthArray([startTime, endTime]);
      const map = this.dateArr.reduce(
        (acc, cur) => ((acc[cur] = true), acc),
        {}
      );
      const result = ranges.some((i) => map[i]);
      console.log('result: ', result);
      return result;
    },
    sameDateArr() {
      const startTime = monent(this.forms.startTime).format('YYYY-MM');
      const endTime = monent(this.forms.endTime).format('YYYY-MM');
      const ranges = createMonthArray([startTime, endTime]);
      const result = ranges.filter((item) => this.dateArr.indexOf(item) > -1);
      return result;
    },
    getParams() {
      const data = {
        ...this.form,
        startTime:
          monent(this.forms.startTime).format('YYYY-MM') + '-01 00:00:00',
        endTime: monent(this.forms.endTime).format('YYYY-MM') + '-01 00:00:00',
        salesGroupName: this.forms.salesGroup,
      };
      return data;
    },
  },
  watch: {
    resKey: {
      handler(val) {
        console.log('val: ????????????', val);
        if (val) {
          console.log('val: ', val);
          this.resDateArr = [];
          this.keys = [];
          console.log('this.keys : ', this.keys);
          this.$emit('update:resKey', false);
        }
      },
    },
    keyArray: {
      handler(val) {
        this.Keys = val;
      },
    },
    visible: {
      handler(val) {
        val && this.searchTableList();
      },
    },
    deleteKeys: {
      handler(val) {
        if (val.length) {
          this.Keys = this.Keys.concat(val).filter(
            (el) => !this.Keys.includes(el) || !val.includes(el)
          );
        } else {
          this.Keys = [];
        }
      },
    },
  },
  async created() {
    this.getSelect();
  },
  mounted() {},
  methods: {
    openDialog(dialog, rowInfo) {
      this[dialog] = true;
      this.currentRowInfo = rowInfo;
      console.log('this.currentRowInfo: ', this.currentRowInfo);
    },
    getSelect() {
      this.rowSelectionMixin.getCheckboxProps = (record) => {
        return {
          props: {
            disabled: this.Keys.indexOf(record.id) !== -1 || !this.isAccord,
          },
        };
      };
    },
    change(pagination) {
      this.paginationMixin.current = pagination.current;
      this.paginationMixin.pageSize = pagination.pageSize;
    },
    async searchTableList() {
      const result = await postPriceChangeTableList(this.getParams);
      this.paginationMixin.total = result.data.data.length;
      this.dataSource = this.proessData(result?.data?.data) || [];
    },
    searchTable() {
      this.searchTableList();
    },
    resForm() {
      this.form = {
        ...defaultForm,
        salesGroupName: this.forms.salesGroup,
      };
      this.searchTableList();
    },
    proessData(data) {
      return (data || []).map((item) => {
        let price = this.dateVal('priceMonth', JSON.parse(item.price));
        let newPrice = this.dateVal('newPriceMonth', JSON.parse(item.newPrice));
        let bpPrice = this.dateVal('bpPriceMonth', JSON.parse(item.bpPrice));
        let rpPrice = this.dateVal('rpPriceMonth', JSON.parse(item.rpPrice));
        return {
          ...item,
          ...price,
          ...newPrice,
          ...bpPrice,
          ...rpPrice,
        };
      });
    },
    dateVal(val, typeObj) {
      let obj = {};
      for (let v in typeObj) {
        obj[`${val}${v}`] = typeObj[v];
      }
      return obj;
    },
    handleCancel() {
      this.rowSelectionMixin.selectedRowKeys = [];
      this.$emit('update:visible', false);
      this.$emit('cancel', false);
    },

    handleOk() {
      const keys = this.rowSelectionMixin.selectedRowKeys;
      if (!keys.length) {
        this.$message.error('请选择客户！');
        return;
      }
      this.Keys = this.Keys.concat(keys);
      this.$emit('select-keys', this.Keys);
      // this.rowSelectionMixin.selectedRows.forEach((item) => {
      //   if (item.price === null) {
      //     item.price = {};
      //   }
      // });
      // const rowData = this.rowSelectionMixin.selectedRows.filter((item) => {
      //   return JSON.parse(item.price);
      // });

      const rowData = this.rowSelectionMixin.selectedRows;

      // rowData.forEach((item) => {
      //   if (item.price !== null) {
      //     const key = Object.keys(JSON.parse(item.price));

      //     const filterKeys = key.filter(
      //       (item) => this.dateArr.indexOf(item) > -1
      //     );
      //     console.log('filterKeys: ', filterKeys, key);
      //     this.resDateArr = this.resDateArr.concat(filterKeys);
      //     // const filterKeys = keys.filter(
      //     //   (item) => this.dateArr.indexOf(item) > -1
      //     // );
      //     // console.log('filterKeys: ', filterKeys);
      //     // this.diffFilterKeys = keys.filter(
      //     //   (item) => this.dateArr.indexOf(item) === -1
      //     // );
      //     // if (filterKeys.length > this.resDateArr.length) {
      //     //   this.resDateArr = filterKeys;
      //     // }
      //   }
      // });
      // this.resDateArr = [...new Set(this.resDateArr)];
      // this.resDateArr = this.resDateArr.sort((a, b) => {
      //   return (
      //     parseInt(a.replace(/\D/g, ''), 7) - parseInt(b.replace(/\D/g, ''), 7)
      //   );
      // });
      // // const current = this.dataSource.find((item) => item.id === keys[0]);
      // // this.$emit(
      // //   'change',
      // //   { key: current.code, label: current.name },
      // //   this.index
      // // );
      // // this.$emit('change', rowData);
      // // this.dateArr.length < this.resDateArr
      // //   ? this.$emit('pass-datearr', {
      // //       dateArr: this.dateArr,
      // //       rowData: rowData,
      // //     })
      // //   : this.$emit('pass-datearr', {
      // //       dateArr: this.resDateArr,
      // //       rowData: rowData,
      // //     });
      this.$emit('pass-datearr', {
        dateArr: this.sameDateArr,
        rowData: rowData,
      });
      this.handleCancel();
    },
  },
};
</script>

<style lang="less" scoped>
.table-list-container {
  margin-top: 20px;
}

.poros-form {
  padding: 10px 20px;
  width: 100%;
  border-bottom: 1px solid #e5e6e9;
}
.poros-form-item {
  width: 25%;
  margin-bottom: 10px;
}
/deep/ .poros-form-item-control-wrapper {
  width: calc(100% - 70px);
}
.btn-search {
  margin-right: 16px;
}
/deep/ .poros-select-selection {
  border: 1px solid #d9d9d9 !important;
}
.row {
  width: 100%;
  justify-content: space-around;
  display: flex;
  float: left;
  &-span {
    float: right;
    line-height: 35px;
    margin-right: 7px;
  }
  &-input {
    width: 70% !important;
    float: right;
  }
  &-div {
    width: 33%;
    height: 35px;
    &-div {
      height: 35px;
      float: right;
    }
  }
}
.button-div {
  width: 13%;
  float: right;
  height: 70px;
}
.button {
  height: 66px !important;
}
.form-div {
  padding: 10px 20px;
  width: 100%;
  background: #fff;
  border: 1px solid #e5e6e9;
  margin-bottom: 10px;
}
.month-span {
  display: inline-block;
  width: 4%;
  text-align: center;
  font-weight: bold;
}
</style>
